package com.gitee.cui.nio.reactor;

import com.gitee.cui.nio.NioDemoConfig;
import com.gitee.cui.util.Logger;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 单线程版本Reactor模式实现控制台输入回显功能
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/20 13:18
 **/
public class SimpleEchoServerReactor implements Runnable {

    public static void main(String[] args) throws IOException {
        new Thread(new SimpleEchoServerReactor()).start();
    }


    /**
     * 选择器
     */
    private Selector selector;

    /**
     * 服务端socket通道
     */
    private ServerSocketChannel serverSocketChannel;

    public SimpleEchoServerReactor() throws IOException {
        selector = Selector.open();
        serverSocketChannel = ServerSocketChannel.open();
        // 服务端监听地址
        InetSocketAddress socketAddress = new InetSocketAddress(NioDemoConfig.SOCKET_SERVER_IP, NioDemoConfig.SOCKET_SERVER_PORT);
        serverSocketChannel.socket().bind(socketAddress);
        Logger.info("服务端已经开始监听：" + socketAddress);
        // 设置为非阻塞通道
        serverSocketChannel.configureBlocking(false);
        // 将通道注册到监听器，并监听accept事件
        SelectionKey selectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        // 对selectionkey添加附件
        selectionKey.attach(new AcceptorHarndler());
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey sk = iterator.next();
                    // 只负责dispatch接收到的事件，具体处理过程由单独的处理类进行处理
                    dispatch(sk);
                }
                selectionKeys.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void dispatch(SelectionKey sk) {
        // 是一个线程
        Runnable handler = (Runnable) sk.attachment();
        // 调用之前attach绑定到选择键的handler处理器对象
        if (handler != null) {
            handler.run();
        }
    }

    /**
     * 新连接处理器
     */
    class AcceptorHarndler implements Runnable {

        @Override
        public void run() {
            try {
                SocketChannel socketChannel = serverSocketChannel.accept();
                Logger.info("接收到一个新连接……");
                if (socketChannel != null) {
                    new EchoHandler(selector, socketChannel);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
